using System;
using System.Linq;
using JNPF.Utils;
using System.Threading.Tasks;
using JNPF.Data;
using JNPF.Data.Util;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using JNPF.Basics.Models;
using System.Data.Common;
using System.Text;
using NPOI.POIFS.FileSystem;

namespace JNPF.Basics.Logic
{
    public class jiushiCustomerconsultantService : DataFactory, jiushiCustomerconsultantIService
    {
        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        public async Task<jiushiCustomerconsultantListOutput> GetInfoResult(int id)
        {
            using (var db = this.Basic)
            {

                var parameters = new List<DbParameter>();
                var dbSql = new StringBuilder();
                dbSql.Append(@"SELECT
	tant.*,
	base.F_CustomerName customerName,
    uu.F_RealName userName ,
	ex.F_RealName partnerUserName,
	Parentex.F_RealName parentPartnerUserName
	
FROM
	jiushi_customerconsultant tant
	LEFT JOIN jiushi_customerbase base ON tant.F_CustomerId = base.F_ID
	LEFT JOIN base_user uu ON tant.F_userid = uu.F_ID
	LEFT JOIN base_user ex ON tant.F_PartnerUserId = ex.F_Id
	LEFT JOIN base_user Parentex ON tant.F_ParentPartnerUserId = Parentex.F_Id 
WHERE
	1 = 1");



                dbSql.Append(" AND tant.F_ID = @id");
                parameters.Add(DataHelper.CreateParameter("@id", id));

                var list = await db.GetListSqlAsync<jiushiCustomerconsultantListOutput>(dbSql.ToString(), parameters.ToArray());

                return list.FirstOrDefault();

            }
        }



        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        public async Task<CustomerconsultantEntity> GetInfo(int id)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<CustomerconsultantEntity>(m => m.Id == id);
            }

        }


        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        public async Task<CustomerconsultantEntity> GetInfoByUuid(string uuid)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<CustomerconsultantEntity>(m => m.Uuid == uuid);
            }

        }


        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns></returns>
        public async Task<CustomerconsultantEntity> GetInfoByCustomerId(int CustomerId)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<CustomerconsultantEntity>(m => m.CustomerId == CustomerId);
            }

        }



        /// <summary>
        /// 列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerconsultantEntity>> GetPageList(jiushiCustomerconsultantListQueryInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<CustomerconsultantEntity>();
                var queryParam = input.queryJson.ToObject();
                //查询业务主键
                //if (!string.IsNullOrEmpty(input.uuid))
                //{
                //    queryWhere = queryWhere.And(m => m.Uuid.Contains(input.uuid));
                //}
                //查询客户ID
                if (input.customerId.ToInt() != 0)
                {
                    queryWhere = queryWhere.And(m => m.CustomerId == input.customerId);
                }
                ////查询顾问次数
                //if (input.number.ToInt() != 0)
                //{
                //    queryWhere = queryWhere.And(m => m.Number == input.number);
                //}
                ////查询配置JSON
                //if (!string.IsNullOrEmpty(input.comConfig))
                //{
                //	queryWhere = queryWhere.And(m => m.ComConfig.Contains(input.comConfig));
                //}
                ////查询合伙人抽佣比例
                //if (input.drawProportion.ToDecimal() > 0)
                //{
                //    queryWhere = queryWhere.And(m => m.DrawProportion == input.drawProportion);
                //}
                ////查询上级抽佣提成比例
                //if (input.parentUserPoints.ToDecimal() > 0)
                //{
                //    //queryWhere = queryWhere.And(m => m.ParentUserPoints == input.parentUserPoints);
                //}
                return await db.GetIQueryable<CustomerconsultantEntity>().Where(queryWhere).GetPageResultAsync(input);
            }
        }


        /// <summary>
        /// 列表（我收到的）
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <returns></returns>
        public async Task<PageResult<jiushiCustomerconsultantListOutput>> GetCusPageList(jiushiCustomerconsultantListQueryInput input)
        {
            using (var db = this.Basic)
            {
                var parameters = new List<DbParameter>();
                var dbSql = new StringBuilder();
                dbSql.Append(@"SELECT
	tant.*,
	base.F_CustomerName customerName,
    uu.F_RealName userName ,
	ex.F_RealName partnerUserName,
	Parentex.F_RealName parentPartnerUserName
	
FROM
	jiushi_customerconsultant tant
	LEFT JOIN jiushi_customerbase base ON tant.F_CustomerId = base.F_ID
	LEFT JOIN base_user uu ON tant.F_userid = uu.F_ID
	LEFT JOIN base_user ex ON tant.F_PartnerUserId = ex.F_Id
	LEFT JOIN base_user Parentex ON tant.F_ParentPartnerUserId = Parentex.F_Id 
WHERE
	1 = 1");

                //企业用户
                if (UserProvider.Instance.Get().RoleIds.ToList().Contains("7037cc3a4a8f4e0f9784b884cd324d54"))
                {
                    //根据
                    var userInfo = await new UserService().GetInfo(UserProvider.Instance.Get().UserId);
                    if (userInfo != null)
                    {
                        var customInfo = await new CustomerbaseService().GetInfoByPhone(userInfo.MobilePhone);
                        if (customInfo != null)
                        {
                            dbSql.Append(" AND  tant.F_CustomerId =@customerId ");
                            parameters.Add(DataHelper.CreateParameter("@customerId", customInfo.Id));
                        }
                    }
                }
                else if (UserProvider.Instance.Get().RoleIds.ToList().Contains("4cbd3517c766476eb4751a6ab0511d53"))
                {
                    //信贷管家
                    dbSql.Append(" AND ( tant.F_UserId =@userId or   tant.F_CreatorUserId =@userId  )");
                    parameters.Add(DataHelper.CreateParameter("@userId", UserProvider.Instance.Get().UserId));
                }
                else
                {
                    //信贷管家
                    dbSql.Append(" AND  tant.F_CreatorUserId =@userId ");
                    parameters.Add(DataHelper.CreateParameter("@userId", UserProvider.Instance.Get().UserId));
                }
                ////关键词（消息标题）
                //if (input.customerld.HasValue)
                //{
                //    dbSql.Append(" AND tant.F_Customerld = @customerld");
                //    parameters.Add(DataHelper.CreateParameter("@customerld", '%' + input.keyword + '%'));
                //}
                input.sidx = "F_CreatorTime";


                return await PageHelper.GetPageResultAsync<jiushiCustomerconsultantListOutput>(db, input, dbSql.ToString(), parameters.ToArray());
            }
        }






        /// <summary>
        /// 创建信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Create(CustomerconsultantEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.InsertAsync(entity);
            }
        }

        /// <summary>
        /// 创建信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task Create(CustomerconsultantEntity entity, CustomerconsultantdetailEntity customerconsultantdetail)
        {
            using (var db = this.Basic)
            {

                await db.BeginTransactionAsync();


                //新增明细
                await db.InsertAsync(customerconsultantdetail);

                if (entity.Id != null && entity.Id > 0)
                {
                    //修改实体
                    await db.UpdateAsync(entity);
                }
                else
                {
                    //第一次新增
                    await db.InsertAsync(entity);
                }
                await db.CommitTransactionAsync();
            }
        }




        /// <summary>
        /// 创建信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task Create(CustomerconsultantEntity entity, CustomerconsultantdetailEntity customerconsultantdetail, List<UserextendEntity> userextendEntities, List<PointsdetailsEntity> pointsdetailsEntities, CustomerbaseEntity customerbaseEntity)
        {
            using (var db = this.Basic)
            {

                await db.BeginTransactionAsync();

                //更新合伙人扩展
                await db.UpdateAsync(userextendEntities);
                await db.InsertAsync(pointsdetailsEntities);
                //新增明细
                await db.UpdateAsync(customerconsultantdetail);

                if (entity.Id != null && entity.Id > 0)
                {
                    //修改实体
                    await db.UpdateAsync(entity);
                }
                else
                {
                    //第一次新增
                    await db.InsertAsync(entity);
                }
                await db.UpdateAsync(customerbaseEntity);
                await db.CommitTransactionAsync();

            }
        }



        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(CustomerconsultantEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.UpdateAsync(entity);
            }
        }


        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task End(CustomerconsultantEntity customerconsultantEntity,CustomerbaseEntity customerbaseEntity, UserEntity userEntity, UserextendEntity userextendEntity)
        {

            using (var db = this.Basic)
            {

                await db.BeginTransactionAsync();

                await db.UpdateAsync(customerconsultantEntity);

                await db.UpdateAsync(customerbaseEntity);
                await db.UpdateAsync(userEntity);

                await db.UpdateAsync(userextendEntity);
                await db.CommitTransactionAsync();
            }
        }



        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Delete(CustomerconsultantEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.DeleteAsync(entity);
            }
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<List<CustomerconsultantEntity>> GetList(jiushiCustomerconsultantListQueryInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<CustomerconsultantEntity>();
                ////查询业务主键
                //if (!string.IsNullOrEmpty(input.uuid))
                //{
                //    queryWhere = queryWhere.And(m => m.Uuid.Contains(input.uuid));
                //}
                ////查询客户ID
                //if (input.customerId.ToInt() != 0)
                //{
                //    queryWhere = queryWhere.And(m => m.CustomerId == input.customerId);
                //}
                ////查询顾问次数
                //if (input.number.ToInt() != 0)
                //{
                //    queryWhere = queryWhere.And(m => m.Number == input.number);
                //}
                ////查询配置JSON
                //if (!string.IsNullOrEmpty(input.comConfig))
                //{
                //	queryWhere = queryWhere.And(m => m.ComConfig.Contains(input.comConfig));
                //}
                ////查询合伙人抽佣比例
                //if (input.drawProportion.ToDecimal() > 0)
                //{
                //    queryWhere = queryWhere.And(m => m.DrawProportion == input.drawProportion);
                //}
                ////查询上级抽佣提成比例
                //if (input.parentUserPoints.ToDecimal() > 0)
                //{
                //    // queryWhere = queryWhere.And(m => m.ParentUserPoints == input.parentUserPoints);
                //}
                return await db.GetIQueryable<CustomerconsultantEntity>().Where(queryWhere).ToListAsync();
            }
        }


    }
}